using System.Data;
using System.Data.SqlClient;
using CoreLibrary;
using CoreLibrary.Sql;
using IBBI.DataBase.Persistent;

namespace IBBI.DataBase.Impl.Sql {

    internal class InsertCategoryAfter : ISqlUpdator<bool> {
        
        private readonly int    _right;
        private readonly string _tableName;
        private readonly Category _item;

        public InsertCategoryAfter(int right, string tableName) {
            _right = right;
            _tableName = tableName;
        }

        public InsertCategoryAfter (int right, string tableName, Category item) {
            _right     = right;
            _tableName = tableName;
            _item      = item;
        }

        public string GetSQL() {
            return string.Format(
               @"
                UPDATE {0} SET RID = RID + 2 WHERE RID > @right;
                UPDATE {0} SET LID = LID + 2 WHERE LID > @right;
                INSERT INTO {0} 
                    (NAME,TITLE,THUMB,TYPE,DESCRIPTION,KEYWORDS,ENABLE,PID,LID,RID,LEVEL,LIST_ORDER,DATE_CREATED,DATE_UPDATED)
                VALUES
                    (@name,@title,@thumb,@type,@description,@keywords,@enable,@pid,@lid,@rid,@level,@listorder,@datecreated,@dateupdated);
               ", 
               _tableName
            );
        }

        public void SetParameters(SqlCommand command) {
            command.Parameters.AddWithValue("@right",       _right);
            command.Parameters.AddWithValue("@name",        Util.GetString(_item.Name));
            command.Parameters.AddWithValue("@title",       Util.GetString(_item.Title));
            command.Parameters.AddWithValue("@thumb",       Util.GetString(_item.Thumb));
            command.Parameters.AddWithValue("@description", Util.GetString(_item.Description));
            command.Parameters.AddWithValue("@keywords",    Util.GetString(_item.Keywords));
            command.Parameters.AddWithValue("@type",        _item.Type);
            command.Parameters.AddWithValue("@enable",      _item.Enable);
            command.Parameters.AddWithValue("@pid",         _item.PID);
            command.Parameters.AddWithValue("@lid",         _item.LID);
            command.Parameters.AddWithValue("@rid",         _item.RID);
            command.Parameters.AddWithValue("@level",       _item.Level);
            command.Parameters.AddWithValue("@listorder",   _item.ListOrder);

            var param1 = command.Parameters.Add(new SqlParameter("@datecreated", SqlDbType.DateTime));
            param1.Value = _item.DateCreated;

            var param2 = command.Parameters.Add(new SqlParameter("@dateupdated", SqlDbType.DateTime));
            param2.Value = _item.DateUpdated;

        }

        public bool GetResult(SqlConnection conn, int result) {
            return result >= 0;
        }

    }

}